﻿using System;
using System.Collections.Specialized;
using System.Data;
using BEGDC.Utility.Castle;

namespace BEGDC.PreContract.BLL
{
    public class ReportField
    {
        public string _fieldname = string.Empty;
        public string _fieldtitle = string.Empty;
        public ReportHelperService.DataType _datetype = ReportHelperService.DataType.String;
        public bool _isTotal;

        public ReportField(string fieldname, string fieldtitle, ReportHelperService.DataType datatype, bool isTotal)
        {
            _fieldname = fieldname;
            _fieldtitle = fieldtitle;
            _datetype = datatype;
            _isTotal = isTotal;
        }

    }

    public class ReportHelperService : IReportHelper
    {
        public enum DataType
        {
            String,
            Date,
            DateTime,
            DoubleN2,
            Boolean

        }

        public enum ReportParameter
        {
            rptType,
            ProvID,
            CATID,
            BDID,
            BGID,
            AsbOrLucent,
            DataType,
            DelayType,
            IsRisk, //Joan 2009-09-30
            Year,
            Month,
            Quater,
            DeliveryType,//zhangwei 2009-07-08
            ContractType,
            CurrentDate,
            DateType,//0-5 <1Month-Total
            ClusterID, //yuliang 2010-5-21
            AdjustID//yuliang 2010-5-21
        }

        public static string SafeSQL(string parameter)
        {
            if (parameter == null)
                return string.Empty;

            parameter = parameter.Replace("'", " ");
            parameter = parameter.Replace(";", " ");

            return parameter;
        }

        public static string GetDetailReportHTML(long employeeID, string permission, NameValueCollection parameters, out string err, out string excelHTML, out string filter)
        {
            string rptTitle = string.Empty;

            filter = string.Empty;

            err = string.Empty;

            excelHTML = string.Empty;

            if (permission != string.Empty)
                filter += permission + " AND ";

            //for report filter inactive BD,CAT,Province
           

            string currentDate = string.Empty;
            ReportHelper.ReportType reportType = new ReportHelper.ReportType();
            #region 解析参数
            foreach (string key in parameters.Keys)
            {
                if (ReportParameter.CurrentDate == (ReportParameter)Enum.Parse(typeof(ReportParameter), key))
                {
                    currentDate = SafeSQL(parameters[key]);
                }
                if (ReportParameter.rptType == (ReportParameter)Enum.Parse(typeof(ReportParameter), key))
                {
                    reportType = (ReportHelper.ReportType)Enum.Parse(typeof(ReportHelper.ReportType), SafeSQL(parameters[key]));
                }
            }
            switch (reportType)
            {
                case ReportHelper.ReportType.ByPuStatusYes:
                case ReportHelper.ReportType.ByProvStatusYes:
                case ReportHelper.ReportType.ByCatStatusYes:
                case ReportHelper.ReportType.ByClusterStatusYes:
                    filter += " StatusID=12 AND";
                    break;
                case ReportHelper.ReportType.ByPuStatusNo:
                case ReportHelper.ReportType.ByProvStatusNo:
                case ReportHelper.ReportType.ByCatStatusNo:
                case ReportHelper.ReportType.ByProvByCATStatusNo:
                    filter += " (StatusID=10 OR StatusID=11)  AND";
                    break;
                default :
                    filter += " BDActive=1 AND CATActive=1 AND ProvinceActive=1 AND ";
                    break;
            }
            foreach (string key in parameters.Keys)
            {

                string value = SafeSQL(parameters[key]);
                ReportParameter parameter = (ReportParameter)Enum.Parse(typeof(ReportParameter), key);
                switch (parameter)
                {
                    case (ReportParameter.rptType):

                        ReportHelper.ReportType type = (ReportHelper.ReportType)Enum.Parse(typeof(ReportHelper.ReportType), value);

                        rptTitle = ReportHelper.GetReportTitle(type, string.Empty, string.Empty, string.Empty);

                        switch (type)
                        {
                            case ReportHelper.ReportType.BlackList:
                                //modified by joan 2008-09-30
                                filter += string.Format("(({0}<'{2}' AND {1}<'{2}') OR ({1} IS NULL AND {0}<'{2}')) AND {3} != {4} AND {3} != {5} AND",
                                    DAL.PreContractInfo.CONST_PromisedDate,
                                    DAL.PreContractInfo.CONST_BlackDate, DateTime.Now.ToString("yyyy-MM-dd"),
                                    DAL.PreContractInfo.CONST_StatusID,
                                    ((int)DicItem.PreContractStatus.Won),
                                    13
                                    );
                                filter += " TypeID<>9 AND";  //filter out 试用合同
                                break;

                        }
                        break;

                    case (ReportParameter.ProvID):
                        filter += string.Format(" {0} = {1} AND ", DAL.PreContractInfo.CONST_ProvinceID, value);
                        break;

                    case (ReportParameter.ClusterID):
                        filter += string.Format(" {0} = {1} AND ", "ClusterID", value);
                        break;

                    case (ReportParameter.BDID):
                        filter += string.Format(" {0} = {1} AND ", DAL.PreContractInfo.CONST_BDID, value);
                        break;

                    case (ReportParameter.CATID):
                        filter += string.Format(" {0} = {1} AND ", DAL.PreContractInfo.CONST_CATID, value);
                        break;

                    case (ReportParameter.BGID):
                        filter += string.Format(" {0} = {1} AND ", "BGID", value);
                        break;

                    case (ReportParameter.AsbOrLucent):
                        if (value == "0" || value == "1")
                            filter += string.Format(" {0} = {1} AND ", DAL.PreContractInfo.CONST_ASBorLucent, value);
                        break;

                    case (ReportParameter.AdjustID):
                        filter += string.Format(" {0} = {1} AND ", "AdjustID", value);
                        break;

                    //modified Joan 2008-09-30 PromisedDate<@DtToday AND DATEADD(mm,3,PromisedDate)>=@DtToday
                    case (ReportParameter.DelayType):
                        if (value == "0-3 Month")
                            filter += string.Format(" (PromisedDate<'{0}' AND DATEADD(mm,3,PromisedDate)>='{0}') AND ", DateTime.Now.ToString("yyyy-MM-dd"));
                        //filter += string.Format(" ({0}<'{1}' AND {0}>='{2}') AND ", BEGDC.PreContract.DAL.PreContractInfo.CONST_PromisedDate, System.DateTime.Now.ToString("yyyy-MM-dd"), System.DateTime.Now.AddMonths(-3).ToString("yyyy-MM-dd"));
                        else if (value == "3-6 Month")
                            filter += string.Format(" (DATEADD(mm,3,PromisedDate)<'{0}' AND DATEADD(mm,6,PromisedDate)>='{0}') AND ", DateTime.Now.ToString("yyyy-MM-dd"));
                        //filter += string.Format(" ({0}<'{1}' AND {0}>='{2}') AND ", BEGDC.PreContract.DAL.PreContractInfo.CONST_PromisedDate, System.DateTime.Now.AddMonths(-3).ToString("yyyy-MM-dd"), System.DateTime.Now.AddMonths(-6).ToString("yyyy-MM-dd"));
                        else if (value == "6-12 Month")
                            filter += string.Format(" (DATEADD(mm,6,PromisedDate)<'{0}' AND DATEADD(mm,12,PromisedDate)>='{0}') AND ", DateTime.Now.ToString("yyyy-MM-dd"));
                        //filter += string.Format(" ({0}<'{1}' AND {0}>='{2}') AND ", BEGDC.PreContract.DAL.PreContractInfo.CONST_PromisedDate, System.DateTime.Now.AddMonths(-6).ToString("yyyy-MM-dd"), System.DateTime.Now.AddMonths(-12).ToString("yyyy-MM-dd"));
                        else if (value == "12-24 Month")
                            filter += string.Format(" (DATEADD(mm,12,PromisedDate)<'{0}' AND DATEADD(mm,24,PromisedDate)>='{0}') AND ", DateTime.Now.ToString("yyyy-MM-dd"));
                        //filter += string.Format(" ({0}<'{1}' AND {0}>='{2}') AND ", BEGDC.PreContract.DAL.PreContractInfo.CONST_PromisedDate, System.DateTime.Now.AddMonths(-12).ToString("yyyy-MM-dd"), System.DateTime.Now.AddMonths(-24).ToString("yyyy-MM-dd"));
                        else if (value == ">24 Month")
                            filter += string.Format(" (DATEADD(mm,24,PromisedDate)<'{0}') AND ", DateTime.Now.ToString("yyyy-MM-dd"));
                        //filter += string.Format(" {0}<'{1}' AND ", BEGDC.PreContract.DAL.PreContractInfo.CONST_PromisedDate, System.DateTime.Now.AddMonths(-24).ToString("yyyy-MM-dd"));
                        else if (value == "Total")
                            filter += string.Format(" PromisedDate<'{0}' AND ", DateTime.Now.ToString("yyyy-MM-dd"));
                        else if (value == "Not Due")
                            filter += string.Format(" PromisedDate>='{0}' AND ", DateTime.Now.ToString("yyyy-MM-dd"));
                        //filter += string.Format(" {0}<'{1}' AND ", BEGDC.PreContract.DAL.PreContractInfo.CONST_PromisedDate, System.DateTime.Now.ToString("yyyy-MM-dd"));

                        filter += string.Format("{0} != {1} AND ",
                            DAL.PreContractInfo.CONST_StatusID,
                            ((int)DicItem.PreContractStatus.Won));

                        break;
                    case (ReportParameter.DeliveryType):
                        if (value == "0-19%" || value == "0-19%<br>Delivered")
                            filter += " (DeliveryPercent>=0 AND DeliveryPercent<20) AND";
                        //filter += string.Format(" ({0}<'{1}' AND {0}>='{2}') AND ", BEGDC.PreContract.DAL.PreContractInfo.CONST_PromisedDate, System.DateTime.Now.ToString("yyyy-MM-dd"), System.DateTime.Now.AddMonths(-3).ToString("yyyy-MM-dd"));
                        else if (value == "20-99%" || value == "20-99%<br>Delivered")
                            filter += " (DeliveryPercent>=20 AND DeliveryPercent<100) AND";
                        //filter += string.Format(" ({0}<'{1}' AND {0}>='{2}') AND ", BEGDC.PreContract.DAL.PreContractInfo.CONST_PromisedDate, System.DateTime.Now.AddMonths(-3).ToString("yyyy-MM-dd"), System.DateTime.Now.AddMonths(-6).ToString("yyyy-MM-dd"));
                        else if (value == "100% Total" || value == "100%<br>Delivered")
                            filter += " (DeliveryPercent=100) AND";
                        //filter += string.Format(" ({0}<'{1}' AND {0}>='{2}') AND ", BEGDC.PreContract.DAL.PreContractInfo.CONST_PromisedDate, System.DateTime.Now.AddMonths(-6).ToString("yyyy-MM-dd"), System.DateTime.Now.AddMonths(-12).ToString("yyyy-MM-dd"));
                        else if (value == "100% delivery normal")
                            filter += " (DeliveryPercent=100 AND (IsDelay=0 OR IsDelay IS NULL)) AND";
                        else if (value == "100% delivery loan/try")
                            filter += " (DeliveryPercent=100 AND IsDelay=1) AND";
                        filter += string.Format(" {0} != {1} AND ",
                            DAL.PreContractInfo.CONST_StatusID,
                            ((int)DicItem.PreContractStatus.Won));
                        break;


                    //Joan 2008-09-30
                    case (ReportParameter.IsRisk):
                        if (value == "Risk")
                        {
                            filter += " IsRisk=1 AND ";
                        }
                        else if (value == "Secure")
                        {
                            filter += " IsRisk=0 AND ";
                        }
                        break;
                    case (ReportParameter.DataType):
                        if (value == "ToBeTransformed")
                            filter += string.Format(" ({0} = {1} OR {2} = {3}) AND ", DAL.PreContractInfo.CONST_StatusID, "10", DAL.PreContractInfo.CONST_StatusID, "11");
                        if (value == "Delivered")
                            filter += string.Format(" ({0} = {1} OR {2} = {3}) AND {4} = 1 AND ", DAL.PreContractInfo.CONST_StatusID, "10", DAL.PreContractInfo.CONST_StatusID, "11", DAL.PreContractInfo.CONST_Delivered);
                        if (value == "Transformed")
                            filter += string.Format(" {0} = {1} AND ", DAL.PreContractInfo.CONST_StatusID, "12"); //should get transformed data for the year

                        break;

                    case (ReportParameter.Year):


                        if (reportType == ReportHelper.ReportType.ByPuStatusYes || reportType == ReportHelper.ReportType.ByProvStatusYes || reportType == ReportHelper.ReportType.ByCatStatusYes)
                        {
                            if (value != string.Empty && int.Parse(value) > 0)
                            {
                                filter += string.Format(" year(SignActual)={0} AND ", value);
                            }
                        }
                        else
                        {
                            if ((value != string.Empty) && (value != SpecialYearQuater.AllYear) && (value != SpecialYearQuater.AfterQuater))
                                filter += string.Format(" ({0} = {1}) AND ", "TradeYear", value);
                            else if (value == SpecialYearQuater.AfterQuater)
                            {
                                ICloseDate iCloseDate = (ICloseDate)AppContainer.Instance[Services.CONST_CloseDate_Service];
                                DataTable dt = iCloseDate.GetCloseDateByDate(DateTime.Now);
                                filter += string.Format(" (  ( TradeYear={0} and TradeQuater>{1}) or TradeYear>{0} ) AND ", dt.Rows[0][DAL.CloseDate.CONST_Year], dt.Rows[0][DAL.CloseDate.CONST_Quarter]);
                            }
                        }
                        break;

                    case (ReportParameter.Month):
                        if (value != string.Empty)
                            filter += string.Format(" ({0} = {1}) AND ", "TradeMonth", value);
                        break;

                    case (ReportParameter.Quater):
                        if (value != string.Empty)
                            filter += string.Format(" ({0} = {1}) AND ", "TradeQuater", value);
                        break;
                    case ReportParameter.ContractType:
                        if (value != string.Empty && int.Parse(value) > 0)
                            filter += string.Format(" ({0} = {1}) AND ", "TypeID", value);
                        break;
                    case ReportParameter.DateType:
                        string queryTerm = string.Empty;
                        switch (reportType)
                        {
                            case ReportHelper.ReportType.ByPuStatusYes:
                            case ReportHelper.ReportType.ByProvStatusYes:
                            case ReportHelper.ReportType.ByCatStatusYes:
                                queryTerm = " DateDiff(day,ERPReceived,SignActual)";
                                break;
                            case ReportHelper.ReportType.ByPuStatusNo:
                            case ReportHelper.ReportType.ByProvStatusNo:
                            case ReportHelper.ReportType.ByCatStatusNo:
                            case ReportHelper.ReportType.ByProvByCATStatusNo:
                                if (currentDate != string.Empty)
                                {
                                    queryTerm = " DateDiff(day,ERPReceived,'" + currentDate + "')";
                                }
                                break;
                        }

                        if (value != string.Empty && queryTerm != string.Empty)
                        {
                            switch (value)
                            {
                                case "0":
                                    filter += queryTerm + "/31<1 AND";
                                    break;
                                case "1":
                                    filter += queryTerm + "/31>=1 AND " + queryTerm + "/31 <3 AND";
                                    break;
                                case "2":
                                    filter += queryTerm + "/31>=3 AND " + queryTerm + "/31 <6 AND";
                                    break;
                                case "3":
                                    filter += queryTerm + "/31>=6 AND " + queryTerm + "/31 <12 AND";
                                    break;
                                case "4":
                                    filter += queryTerm + "/31>=12 AND ";
                                    break;
                                case "5":
                                    //Total
                                    break;

                            }
                        }



                        break;

                }
            }

            if (filter.EndsWith("AND "))
                filter = filter.Substring(0, filter.Length - 4);

            return string.Empty;
            #endregion

            #region obsolete
            //ArrayList arrData = new ArrayList();
            //#region build column arraylist Modified by joan 2009-09-30 add currentsituation , sign due, IsRisk

            //arrData.Add(new ReportField("PreContractType", "Category", ReportHelperService.DataType.String, false));
            //arrData.Add(new ReportField("PreContractStatus", "Status", ReportHelperService.DataType.String, false));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.PreContractInfo.CONST_PreContractNo, "Pre-Contract No", ReportHelperService.DataType.String, false));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.BG.CONST_BGCode, "BG", ReportHelperService.DataType.String, false));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.BD.CONST_BDCode, "BD", ReportHelperService.DataType.String, false));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.Product.CONST_ProductName, "Product", ReportHelperService.DataType.String, false));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.Province.CONST_ProvinceCName, "Province", ReportHelperService.DataType.String, false));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.CAT.CONST_CATCode, "CAT", ReportHelperService.DataType.String, false));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.PreContractInfo.CONST_PromisedDate, "Promised Date", ReportHelperService.DataType.Date, false));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.PreContractInfo.CONST_SignActual, "Transfer Date", ReportHelperService.DataType.Date, false));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.PreContractInfo.CONST_ERPReceived, "ERP Accept", ReportHelperService.DataType.Date, false));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.PreContractInfo.CONST_Delivered, "Delivered", ReportHelperService.DataType.Boolean, false));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.PreContractInfo.CONST_DeliveryPercent, "Delivery Percentage%", ReportHelperService.DataType.DoubleN2, false));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.PreContractInfo.CONST_CurrentSituation, "CurrentSituation", ReportHelperService.DataType.String, false));
            //arrData.Add(new ReportField("CEWME", "CEW ME", ReportHelperService.DataType.DoubleN2, true));
            //arrData.Add(new ReportField("OrionME", "Orion ME", ReportHelperService.DataType.DoubleN2, true));
            //arrData.Add(new ReportField("GAP", "GAP", ReportHelperService.DataType.DoubleN2, true));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.PreContractInfo.CONST_SignDue, "Sign Due", ReportHelperService.DataType.Date, false));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.PreContractInfo.CONST_TradeMonth, "TradeMonth", ReportHelperService.DataType.String, false));
            //arrData.Add(new ReportField(BEGDC.PreContract.DAL.PreContractInfo.CONST_IsRisk, "Risk", ReportHelperService.DataType.Boolean, false));


            //#endregion

            //#region build html

            //System.Text.StringBuilder sbTitle = new StringBuilder();
            //System.Text.StringBuilder sbTable = new StringBuilder();
            //System.Text.StringBuilder sbTotal = new StringBuilder();

            //BEGDC.PreContract.BLL.IPreContractInfo precontractService = (BEGDC.PreContract.BLL.IPreContractInfo)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_PreContractInfo_Service];
            //System.Data.DataTable dt = precontractService.GetPreContractInfo(filter);

            //bool isHead = true;

            ////如果有数据, 加入Total行.
            //System.Data.DataRow drTotal = dt.NewRow();
            //if (dt.Rows.Count > 0)
            //{
            //    drTotal = dt.NewRow();
            //    dt.Rows.Add(drTotal);
            //}

            //sbTitle.Append("<table bgcolor=\"black\" border=\"0\" cellpadding=\"2\" cellspacing=\"1\">");

            ////循环数据. 
            //foreach (System.Data.DataRow dr in dt.Rows)
            //{
            //    if (isHead)
            //    {
            //        sbTitle.Append("<tr class=\"row_title\">");
            //    }
            //    if (dr.RowState == DataRowState.Added)
            //        sbTotal.Append("<tr class=\"row_total\">");
            //    else
            //        sbTable.Append("<tr class=\"row_body\">");


            //    int iFieldIndex = 0;
            //    //循环输出字段
            //    foreach (ReportField field in arrData)
            //    {
            //        iFieldIndex++;
            //        if (isHead)
            //        {
            //            sbTitle.Append(string.Format("<td class=\"title_month\">{0}</td>", field._fieldtitle));
            //        }

            //        string fieldvalue = string.Empty;

            //        switch (field._datetype)
            //        {
            //            case ReportHelperService.DataType.String:
            //                if (!(dr[field._fieldname] is DBNull))
            //                    fieldvalue = dr[field._fieldname].ToString();
            //                break;
            //            case ReportHelperService.DataType.Boolean:
            //                if (!(dr[field._fieldname] is DBNull))
            //                    fieldvalue = Convert.ToBoolean(dr[field._fieldname]).ToString();
            //                break;
            //            case ReportHelperService.DataType.Date:
            //                if (!(dr[field._fieldname] is DBNull))
            //                    fieldvalue = Convert.ToDateTime(dr[field._fieldname]).ToString("yyyy-MM-dd");
            //                break;

            //            case ReportHelperService.DataType.DateTime:
            //                if (!(dr[field._fieldname] is DBNull))
            //                    fieldvalue = dr[field._fieldname].ToString();
            //                break;

            //            case ReportHelperService.DataType.DoubleN2:
            //                if (!(dr[field._fieldname] is DBNull))
            //                {
            //                    fieldvalue = Convert.ToDouble(dr[field._fieldname]).ToString("N2");
            //                    if (field._isTotal)
            //                    {
            //                        if (drTotal[field._fieldname] is DBNull)
            //                            drTotal[field._fieldname] = 0;  
            //                        drTotal[field._fieldname] = Convert.ToDouble(drTotal[field._fieldname]) + Convert.ToDouble(dr[field._fieldname]);
            //                    }
            //                }
            //                break;
            //        }



            //        if (dr.RowState == DataRowState.Added)
            //        {
            //            if (iFieldIndex == 1)
            //                fieldvalue = "Total";
            //            sbTotal.Append(string.Format("<td>{0}</td>", fieldvalue));
            //        }
            //        else
            //            sbTable.Append(string.Format("<td>{0}</td>", fieldvalue));

            //    }

            //    if (dr.RowState == DataRowState.Added)
            //        sbTotal.Append("</tr>");
            //    else
            //        sbTable.Append("</tr>");

            //    if (isHead)
            //    {
            //        sbTitle.Append("</tr>");
            //    }
            //    isHead = false;
            //}


            //sbTitle.Append(sbTable.ToString());
            //sbTitle.Append(sbTotal.ToString());
            //sbTitle.Append("</table>");

            ////sbTitle.Insert(0, rptTitle);



            //#endregion
            //return sbTitle.ToString();
            #endregion
            return string.Empty;

        }

    }
}



